package com.heba.fragment.mine;

import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.AppManager;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.ItemShareObject;
import com.heba.bean.PhotoObject;
import com.heba.bean.ShareObject;
import com.heba.bean.user.UserObject;
import com.heba.config.CommonConfig;
import com.heba.dialog.CustomDialogView;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.GuideActivity;
import com.heba.greenmulu.MainActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.WebviewActivity;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.greenmulu.blockUser.BlockUserListActivity;
import com.heba.greenmulu.changeaccount.ChangeAccountActivity;
import com.heba.greenmulu.diary.ItemDiaryAddActivity;
import com.heba.greenmulu.user.UserAboutActivity;
import com.heba.greenmulu.user.UserArticleActivity;
import com.heba.greenmulu.user.UserContributionActivity;
import com.heba.greenmulu.user.UserDiaryFavoriteActivity;
import com.heba.greenmulu.user.UserEditActivity;
import com.heba.greenmulu.user.UserLanguageActivity;
import com.heba.greenmulu.user.UserNotificationActivity;
import com.heba.greenmulu.user.UserProductActivity;
import com.heba.greenmulu.user.UserProductReviewActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.popupwindow.SharePopupWindow;
import com.heba.popupwindow.callback.ShareListener;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.IndicatorLineUtil;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 我的頁面
 * Created by jason on 2020/1/2.
 */
public class MineNewFragment extends BaseFragment implements View.OnClickListener {


    private View view_background;
    /**
     * 控制右侧菜单栏
     */
    private DrawerLayout drawer;

    /**
     * topbar
     */
    private ImageView img_diary_write;
    private ImageView img_setting;
    private TextView txt_mine_title;

    /**
     * account view
     */
    private ImageView img_avatar;
    private ImageView img_copy_link;
    private TextView txt_edit_account;
    private TextView txt_nickname;
    private TextView txt_desc;
    private int selectIndex = 0;
    private LinearLayout linearLayout;
    private AppBarLayout appBarLayout;
    private float avatarTop;
    private float minTop = 15;
    private float bannarHeight ;
    /**
     * tablayout
     */
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;
    private ConstraintLayout bottomLine1;
    private ConstraintLayout bottomLine2;
    private ImageView bannar_image;
    /**
     * fragment
     */
    private MineSelectPhotoFragment mineSelectPhotoFragment;
    private MineSelectFriendsFragment mineSelectFriendsFragment;
    private ArrayList<Fragment> fragments = new ArrayList<>();

    private String buddyUserID;
    private UserObject userObject;

    /**
     * 分享彈出框
     */
    private SharePopupWindow sharePopupWindow;
    private ShareObject shareObject;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Debug.LogError(TAG, "onCreateView");
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_mine_new, container, false);
        initView(view);
        setSettingTextView(view);
        initClickListener();
        setDrawerLayout();
        initFragments();
        setCustomTabView();
        initPopupWindow();
        return view;
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        view_background = view.findViewById(R.id.view_background);
        drawer = view.findViewById(R.id.drawer_layout);
        img_diary_write = view.findViewById(R.id.img_diary_write);
        img_setting = view.findViewById(R.id.img_setting);
        txt_mine_title = view.findViewById(R.id.txt_mine_title);
        img_avatar = view.findViewById(R.id.img_avatar);
        img_copy_link = view.findViewById(R.id.img_copy_link);
        txt_edit_account = view.findViewById(R.id.txt_edit_account);
        txt_nickname = view.findViewById(R.id.txt_nickname);
        txt_desc = view.findViewById(R.id.txt_desc);
        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.viewPager);
        bottomLine1 = view.findViewById(R.id.bottom_line_1);
        bottomLine2 = view.findViewById(R.id.bottom_line_2);
        shareObject = new ShareObject();
        txt_mine_title.setText(Cfg.Account);
        buddyUserID = Cfg.UserID;
        bannar_image = view.findViewById(R.id.bannar_image);
        linearLayout = view.findViewById(R.id.linear_top);
        appBarLayout = view.findViewById(R.id.appbar);
        Resources resources = getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density1 = dm.density;
        float width3 = dm.widthPixels;
        bannarHeight = width3/16*9;
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        Debug.LogError(TAG, "onVisible");
        getUserInfoData();
        drawer.closeDrawer(GravityCompat.END);
    }

    /**
     * 分享彈出框
     */
    private void initPopupWindow() {
        List<ItemShareObject> shareList1 = new ArrayList<>();
        List<ItemShareObject> shareList2 = new ArrayList<>();

        /**
         * 分享至社交軟件
         */
        int[] ids = {R.drawable.icon_more_share_facebook, R.drawable.icon_more_share_whatsapp, R.drawable.icon_more_share_wechat, R.drawable.icon_more_message};
        String[] contents = this.getResources().getStringArray(R.array.share_contents_friends_invite);
        int[] shareTypes = {CommonConfig.SHARE_TO_FACEBOOK, CommonConfig.SHARE_TO_WHATSAPP, CommonConfig.SHARE_TO_WECHAT, CommonConfig.SHARE_TO_SMS};
        for (int i = 0; i < ids.length; i++) {
            ItemShareObject shareObject = new ItemShareObject();
            shareObject.setImageID(ids[i]);
            shareObject.setShareContent(contents[i]);
            shareObject.setShareType(shareTypes[i]);
            shareList1.add(shareObject);
        }
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                getTop();
                float height = DensityUtils.dip2px(getContext(),bannarHeight);
                float top = avatarTop;
                if (top <=295){
                }
//                bannar_image.setAlpha((avatarTop-200)/(bannarHeight-200));

            }
        });
        sharePopupWindow = new SharePopupWindow(getActivity(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        sharePopupWindow.setShareTitle(getResources().getString(R.string.share_friend_invite));
        sharePopupWindow.hideShareLine();
        sharePopupWindow.setShareList(shareList1, shareList2);

        /**
         * 設置分享監聽
         */
        sharePopupWindow.setOnShareListener(new ShareListener(getContext()) {
            @Override
            public void shareSMS() {
                //短信分享個人名片
                if (null != userObject) {
                    Uri smsToUri = Uri.parse("smsto:");
                    Intent mIntent = new Intent(Intent.ACTION_SENDTO, smsToUri);
//                    mIntent.putExtra("sms_body", String.format(getActivity().getResources().getString(R.string.share_account_to_sms),
//                            userObject.getNickname(), userObject.getLink()));
                    mIntent.putExtra("sms_body", String.format(getActivity().getResources().getString(R.string.share_greenmulu_text1), Cfg.Account)
                            + "\n" + Cfg.ShareLink);
                    getActivity().startActivity(mIntent);
                }
            }
        });

        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                view_background.setVisibility(View.GONE);
            }
        });
    }
    private void getTop(){
        int[] viewLocation = new int[2];
        img_avatar.getLocationInWindow(viewLocation);
        avatarTop = viewLocation[1];
    }
    /**
     * initClickListener
     */
    private void initClickListener() {
        img_diary_write.setOnClickListener(this);
        img_setting.setOnClickListener(this);
        txt_edit_account.setOnClickListener(this);
    }

    /**
     * initFragments
     */
    private void initFragments() {
        mineSelectPhotoFragment = MineSelectPhotoFragment.newInstance(buddyUserID);
        mineSelectFriendsFragment = MineSelectFriendsFragment.newInstance(buddyUserID);
        fragments.add(mineSelectPhotoFragment);
        fragments.add(mineSelectFriendsFragment);
    }

    /**
     * 设置自定义tab
     */
    private void setCustomTabView() {
        /**
         * 添加tab
         */
        for (int i = 0; i < 2; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getChildFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        Objects.requireNonNull(tabLayout.getTabAt(0)).setCustomView(getTabItemView(R.drawable.image_post_selector));
        Objects.requireNonNull(tabLayout.getTabAt(1)).setCustomView(getTabItemView(R.drawable.image_friends_selector));

        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                int width3 = dm.widthPixels;
                TranslateAnimation translateAnimation1 = new TranslateAnimation(selectIndex*(width3/2),position*(width3/2),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();



                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    /**
     * 获取itemview
     *
     * @param icon
     * @return
     */
    private View getTabItemView(int icon) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_tab_layout, null);
        ImageView iv_icon = view.findViewById(R.id.iv_icon);
        iv_icon.setImageResource(icon);
        return view;
    }

    /**
     * Set DrawerLayout totally transparent.
     */
    private void setDrawerLayout() {
        drawer.setFitsSystemWindows(true);
        drawer.setClipToPadding(false);
    }

    /**
     * 获取设置布局item
     *
     * @param view
     */
    private void setSettingTextView(View view) {
        int[] viewIDs = new int[]{R.id.view_follow,  R.id.view_article,
                R.id.view_product,R.id.view_diary,  R.id.view_review, R.id.view_product_contribute,R.id.view_block,R.id.view_change_account,
                R.id.view_language, R.id.view_notification, R.id.view_about, R.id.view_privacy, R.id.view_terms, R.id.view_logout};

        String[] strTexts = getResources().getStringArray(R.array.mine_setting_datas);

        Class[] actClass = {null, UserArticleActivity.class, UserProductActivity.class,
                UserDiaryFavoriteActivity.class, UserProductReviewActivity.class, UserContributionActivity.class,BlockUserListActivity.class, ChangeAccountActivity.class, UserLanguageActivity.class,
                UserNotificationActivity.class, UserAboutActivity.class, WebviewActivity.class, WebviewActivity.class, null};

        for (int i = 0; i < strTexts.length; i++) {
            findSettingTextView(view, viewIDs[i], strTexts[i], actClass[i]);
        }
    }

    /**
     * @param view
     * @param viewID
     * @param text
     */
    private void findSettingTextView(View view, int viewID, String text, Class<?> activity) {
        View targetView = view.findViewById(viewID);
        TextView textView = targetView.findViewById(R.id.textview);
        textView.setText(text);

        //隱藏封鎖的賬戶
//        if (viewID == R.id.view_account) {
//            targetView.setVisibility(View.GONE);
//        }

        /**
         * 跳轉相對應頁面
         */
        targetView.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            switch (viewID) {
                case R.id.view_follow:
                    if (null == userObject)
                        return;
//                    shareObject.setShareTitle(String.format(this.getResources().getString(R.string.share_account_title), userObject.getNickname()));
//                    shareObject.setShareContent(String.format(this.getResources().getString(R.string.share_account_content), userObject.getNickname()));
//                    shareObject.setShareImageUrl(userObject.getIcon());
//                    shareObject.setShareLink(userObject.getLink());
                    shareObject.setShareTitle(getActivity().getResources().getString(R.string.app_name));
                    shareObject.setShareContent(String.format(getActivity().getResources().getString(R.string.share_greenmulu_text1), Cfg.Account));
                    shareObject.setShareImageUrl(Cfg.ShareImageUrl);
                    shareObject.setShareLink(Cfg.ShareLink);
                    sharePopupWindow.setShareObject(shareObject);
                    view_background.setVisibility(View.VISIBLE);
                    sharePopupWindow.showAtLocation(targetView, Gravity.BOTTOM, 0, 0);
                    return;
                case R.id.view_account:
                    return;
                case R.id.view_privacy:
                    bundle.putString(CommonConfig.WEBVIEW_TITLE, getResources().getString(R.string.privacy_policy));
                    bundle.putString(CommonConfig.WEBVIEW_URL, Cfg.PrivacyUrl);
                    break;
                case R.id.view_terms:
                    bundle.putString(CommonConfig.WEBVIEW_TITLE, getResources().getString(R.string.term_of_use));
                    bundle.putString(CommonConfig.WEBVIEW_URL, Cfg.TermsUseUrl);
                    break;
                case R.id.view_block:
//                    openActivity(BlockUserListActivity.class);
                    break;
                case R.id.view_logout:
                    //登出
                    new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                        @Override
                        public void onYesClick() {
                            MemberShipHelper.logOut();
                            openActivity(MainActivity.class);
                            AppManager.getAppManager().finishAllActivity();
                        }

                        @Override
                        public void onNoClick() {

                        }
                    }).showDialog(getActivity(), getResources().getString(R.string.confirm_logout), "");
                    return;
                default:
                    break;
            }
            openActivity(activity, bundle);
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_diary_write:
                openActivity(ItemDiaryAddActivity.class);
                break;
            case R.id.img_setting:
                if (drawer.isDrawerOpen(GravityCompat.END)) {
                    drawer.closeDrawer(GravityCompat.END);
                } else {
                    drawer.openDrawer(GravityCompat.END);
                }
                break;
            case R.id.txt_edit_account:
                if (userObject != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(CommonConfig.USER_OBJECT, userObject);
                    openActivity(UserEditActivity.class, bundle);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 更新用戶信息View
     */
    private void updatePersonInfoView(UserObject object) {
        mineSelectPhotoFragment.setPostCount(Integer.parseInt(object.getDiaryCount()));
        mineSelectPhotoFragment.setTaggedCount(object.getPasteCount());
        mineSelectFriendsFragment.setFollowingCount(object.getTrackCount());
        mineSelectFriendsFragment.setFollowerCount(object.getFanCount());
        txt_mine_title.setText(object.getAccount());
        txt_nickname.setText(object.getNickname());
        txt_desc.setText(CommonUtils.getDecodeText(object.getProfile()));
        Cfg.change("Account", object.getAccount());
        Cfg.change("NickName", object.getNickname());
        Cfg.change("Icon", object.getIcon());
        Cfg.save();
        GlideUtil.loadImageWithPlaceHolderID(getActivity(), object.getIcon(), img_avatar, R.drawable.icon_head_portrait);

        /**
         * 复制网站地址
         */
        img_copy_link.setVisibility(userObject.getWebside().isEmpty() ? View.INVISIBLE : View.VISIBLE);
        img_copy_link.setOnClickListener(v -> {
            if (!userObject.getWebside().isEmpty()) {
                ToastShow.displayToast(getActivity(), getActivity().getResources().getString(R.string.mine_copy_link));
                CommonUtils.copyText2Clipboard(getActivity(), userObject.getWebside());
            }
        });

        /**
         * 查看頭像大圖
         */
        img_avatar.setOnClickListener(v -> {
            List<PhotoObject> list = new ArrayList<>();
            PhotoObject photoObject = new PhotoObject();
            photoObject.setImageUrl(object.getIcon());
            list.add(photoObject);
            Bundle bundle = new Bundle();
            bundle.putInt(CommonConfig.TYPE, 1);
            bundle.putSerializable(CommonConfig.PHOTOLIST, (Serializable) list);
            openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle);
        });
    }

    /**
     * 獲取用戶個人信息數據
     */
    private void getUserInfoData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("BuddyUserID", Cfg.UserID);
        client.get(Cfg.BaseUrl + "/User/GetBuddyInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            userObject = new Gson().fromJson(jsonObject.toString(), UserObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        /**
                         * 顯示用戶個人信息
                         */
                        if (null != userObject) {
                            updatePersonInfoView(userObject);
                        }
                        Resources resources = getResources();
                        DisplayMetrics dm = resources.getDisplayMetrics();
                        float density1 = dm.density;
                        int width3 = dm.widthPixels;
                        ViewGroup.LayoutParams linearParams = linearLayout.getLayoutParams();
                        if (userObject.getBannerUrl().length() <= 0 ){
                            linearParams.height = 170;
                            bannar_image.setVisibility(View.INVISIBLE);

                        }else {
                            bannar_image.setVisibility(View.VISIBLE);

                            linearParams.height = width3/16*9;

                            GlideUtil.loadImageWithDefaultPlaceHolder(getContext(),userObject.getBannerUrl(),bannar_image);
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals(CommonConfig.DIARY_REFRESH)) {
            if (null != tabLayout && tabLayout.getTabCount() > 0) {
                tabLayout.getTabAt(0).select();
            }
        }
        if (event.getEvent().equals(CommonConfig.CLOSE_DRAWER)){
            drawer.closeDrawer(GravityCompat.END);
        }
    }

}
